const http = require('http');
const express = require('express')
const bodyParser = require('body-parser');
const cors = require('cors')
const bcrypt = require('bcrypt');
const app = express()
const port = 3000
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const {User,Word} = require('./module')
const {initializeSocketIO,rooms} = require('./socket')
const users = [{username:'1a',password:'a1'},{username:'2b',password:'b2'}]
const user = []
const url = "101.132.154.15";
const word = [{wordname:'animal',wordscript:'isanimal',wordcontent:['bird','dog','cat'],worduser:'a1'}]

const server = http.createServer(app).listen(port, ()=> {
    console.log(`linsten on ${port}`)
});
app.use(cors({
    origin: 'http://101.132.154.15:8090' // 允许来自 http://localhost:8090 的请求访问该资源
  }))

app.get('/rooms',async(req,res) =>{
    res.send(rooms)
    console.log('sendroom')
})

app.post('/register',async(req,res) =>{
    const tuser = await User.findOne({
        username:req.body.username,
    })
    if(tuser){
        return res.send({
            message:'用户名已存在'
        })
    }
    const user = await User.create({
        username:req.body.username,
        password:req.body.password
    })
    res.send({user,message:'注册成功'})
    console.log('注册')
})//注册请求

app.post('/wordstorage',async(req,res) =>{
    console.log(req.body.username)
    const user = await User.findOne({
        username:req.body.username,
    })
    if(!user){
        return res.send({
            message:'用户不存在'
        })
    }
    const words = user.userword || []
    const word = await Word.find().lean()
    const publicWords = word.map(({wordowner, wordname}) => ({wordowner, wordname}))
    res.send({words,publicWords})
    console.log(publicWords)
})//词库请求

app.post('/choseword',async(req,res) =>{
    console.log(req.body.username)
    const word = await Word.findOne({ wordowner: req.body.wordowner, wordname: req.body.wordname });
    const user = await User.findOne({
        username:req.body.username,
    })
    if (user && user.userword.some(word => word.wordowner === req.body.wordowner && word.wordname === req.body.wordname)) {
        console.log("已有词库");
      } else {
        const newWord = {
            wordowner: req.body.wordowner,
            wordname: req.body.wordname,
          };
          
          await User.updateOne(
            { _id: user._id },
            { $push: { userword: newWord } }
          );
        console.log("添加词库");
      }
    res.send(word)
})//词库请求

app.post('/login',async(req,res) =>{
    const user = await User.findOne({
        username:req.body.username,
    })
    if(!user){
        return res.send({
            message:'用户不存在'
        })
    }
    const isPass = bcrypt.compareSync(
        req.body.password,
        user.password
    )
    if(!isPass)
    {
        return res.send({
            message:'密码错误'
        })
    }
    res.send({user,message:'登录成功'})
    console.log('登录')
})

app.post('/createWord',async(req,res) =>{
    const word = await Word.create({
        wordname: req.body.wordname,
        worddscript:req.body.worddscript,
        wordowner:req.body.wordowner,
        wordcontent:req.body.wordcontent,
    })
    res.send({word,message:'上传成功'})
    console.log('创建词库')
})//注册请求

initializeSocketIO(server)

console.log('Server running at http://127.0.0.1:3000/');